#!/bin/bash

# Qdrant向量数据库初始化脚本
# 用于创建WMS知识库集合和配置

echo "🚀 初始化Qdrant向量数据库..."

# Qdrant服务地址
QDRANT_URL="http://localhost:6333"
COLLECTION_NAME="wms_knowledge"

# 等待Qdrant服务启动
echo "⏳ 等待Qdrant服务启动..."
until curl -s "$QDRANT_URL/collections" > /dev/null; do
    echo "等待Qdrant服务启动..."
    sleep 2
done

echo "✅ Qdrant服务已启动"

# 检查集合是否存在
echo "🔍 检查集合是否存在..."
COLLECTION_EXISTS=$(curl -s "$QDRANT_URL/collections/$COLLECTION_NAME" | jq -r '.status' 2>/dev/null)

if [ "$COLLECTION_EXISTS" = "ok" ]; then
    echo "✅ 集合 $COLLECTION_NAME 已存在"
else
    echo "📝 创建集合 $COLLECTION_NAME..."
    
    # 创建集合
    curl -X PUT "$QDRANT_URL/collections/$COLLECTION_NAME" \
        -H "Content-Type: application/json" \
        -d '{
            "vectors": {
                "size": 384,
                "distance": "Cosine"
            },
            "optimizers_config": {
                "default_segment_number": 2
            },
            "replication_factor": 1
        }'
    
    if [ $? -eq 0 ]; then
        echo "✅ 集合 $COLLECTION_NAME 创建成功"
    else
        echo "❌ 集合创建失败"
        exit 1
    fi
fi

# 创建索引（可选）
echo "📊 创建索引..."
curl -X PUT "$QDRANT_URL/collections/$COLLECTION_NAME/index" \
    -H "Content-Type: application/json" \
    -d '{
        "field_name": "knowledge_id",
        "field_schema": "integer"
    }'

# 显示集合信息
echo "📋 集合信息："
curl -s "$QDRANT_URL/collections/$COLLECTION_NAME" | jq '.'

echo "🎉 Qdrant向量数据库初始化完成！"
echo ""
echo "📝 使用说明："
echo "1. 集合名称: $COLLECTION_NAME"
echo "2. 向量维度: 384 (OpenAI text-embedding-ada-002)"
echo "3. 距离算法: Cosine"
echo "4. API地址: $QDRANT_URL"
echo ""
echo "🔧 测试连接："
echo "curl $QDRANT_URL/collections/$COLLECTION_NAME"
